<template>
  <div>
    <van-form @submit="bookTypeOnSubmit" required>
      <van-cell-group inset>
        <van-field
          v-model="typeModel"
          input-align="right"
          is-link
          readonly
          name="picker"
          label="打卡类型"
          placeholder="点击选择打卡类型"
          @click="typeOnChange"
          :rules="[{ required: true, message: '请选择打卡类型' }]"
        />
        <van-popup v-model:show="typeShowPicker" position="bottom">
          <van-picker
            :columns="state.typeColumns"
            @confirm="typeOnConfirm"
            @cancel="typeOnCancel"
          />
        </van-popup>

        <van-field
          v-model="taskForm.title"
          input-align="right"
          label="标题"
          placeholder="请输入标题"
          :rules="[{ required: true, message: '请输入标题' }]"
        />
        <van-field
          v-model="taskForm.content"
          label-align="top"
          label="内容"
          placeholder="请输入内容"
          rows="3"
          autosize
          type="textarea"
          maxlength="100"
          show-word-limit
          :rules="[{ required: true, message: '请输入内容' }]"
        />
        <van-field
          v-model="taskForm.price"
          input-align="right"
          label="金额"
          type="number"
          placeholder="请输入金额"
          :rules="[{ required: true, message: '请输入金额' }]"
        />
        <van-field name="uploader" label-align="top">
          <template #input>
            <van-uploader
              accept="video/*,image/*"
              preview-size="94px"
              @delete="uploadDelete"
              result-type="file"
              v-model="fileList"
              :max-count="5"
              :after-read="afterRead"
            />
          </template>
        </van-field>
      </van-cell-group>
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script setup>
import { useAppStore, useUserStore } from "../../stores";
import { computed, reactive, ref, toRefs } from "vue";
import dayjs from "dayjs";
import { createUserTask } from "@/service/task";
import { getBookListSelect } from "@/service/book";
import { useRouter } from "vue-router";
import { showToast, showSuccessToast } from "vant";

import { uploadFile } from "../../service/file";
import axios from "axios";

const URL = axios.defaults.baseURL;

const appStore = useAppStore();
const userStore = useUserStore();

const router = useRouter();

const typeModel = computed(() => {
  const typeMap = new Map(state.typeColumns.map((item) => [item.value, item]));
  return taskForm.value.type && typeMap.get(taskForm.value.type).text;
});

const state = reactive({
  typeColumns: [
    { text: "学习", value: 1 },
    { text: "表现", value: 2 },
    { text: "其他", value: 3 },
  ],
});

const typeShowPicker = ref(false);
const typeOnChange = (e) => {
  typeShowPicker.value = true;
};

const typeOnConfirm = ({ selectedOptions }) => {
  taskForm.value.type = selectedOptions[0]?.value;
  typeShowPicker.value = false;
};

const typeOnCancel = (e) => {
  typeShowPicker.value = false;
};

const data = reactive({
  taskForm: {
    type: null, //类型 1 学习 2 表现 3 其他
    time: dayjs(new Date()).format("YYYY-MM-DD HH:ss"), //	时间
    title: "", //	标题
    content: "", //	内容
    resource: "", //图片或视频资源 json格式
    bookIds: "", //	图书ids
    price: "", //单位 ，显示的显示元 保留两个小数点
  },
});
const { taskForm } = toRefs(data);

//图片上传相关
const fileList = ref([]);
const resourceList = ref([]);

//图片上传loading
const afterRead = async (file) => {
  file.status = "uploading";
  file.message = "上传中...";
  const { data, status } = await uploadFile(file.file);
  if (status == 0) {
    file.status = "success";
    file.message = "上传成功";
    file.name = data;
    resourceList.value = resourceList.value.concat({
      url: `${URL}${data}`,
      name: data,
    });
  }
};

//上传 - 删除
const uploadDelete = (file) => {
  resourceList.value = resourceList.value.filter((o) => o.name != file.name);
  showSuccessToast("删除成功");
};

//表单提交
const bookTypeOnSubmit = async () => {
  const { status } = await createUserTask({
    ...taskForm.value,
    ...{
      price: taskForm.value.price * 100,
      resource: JSON.stringify(resourceList.value),
    },
  });
  if (status == 0) {
    showSuccessToast("新增成功");
    taskForm.value = {
      type: null, //类型 1 学习 2 表现 3 其他
      time: dayjs(new Date()).format("YYYY-MM-DD HH:ss"), //	时间
      title: "", //	标题
      content: "", //	内容
      resource: "", //图片或视频资源 json格式
      bookIds: "", //	图书ids
      price: "", //单位 ，显示的显示元 保留两个小数点
    };
  }
};
</script>

<style scoped lang="less"></style>
